package com.hyd.project;

import java.io.File;
import java.util.Calendar;
import mirko.android.datetimepicker.date.DatePickerDialog;
import mirko.android.datetimepicker.date.DatePickerDialog.OnDateSetListener;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 编辑个人信息界面
 * 
 * @author llf
 * 
 */
public class EditPersonalInfoActivity extends Activity {
	private TextView birthday;
	private DatePickerDialog datepickrDialog;
	private Dialog dialog;
	private AlertDialog sexDialog;
	private RelativeLayout choice_photo, sex_dialog;
	private Calendar calendar = Calendar.getInstance();
	private TextView male, female, sex, address;
	private Button camera, album, cancel;
	private File tempFile;
	private ImageView portrait;
	private final static int ADDRESS = 1, CAMERA = 101, ALBUM = 100,
			CROP = 102;
	private final static String TEMP = "phone.jpg";
	private boolean isSDCardExit;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_edit_personal_info);

		initView();
		initClick();
	}

	private void initView() {
		portrait = (ImageView) findViewById(R.id.portrait);
		sex = (TextView) findViewById(R.id.sex);
		birthday = (TextView) findViewById(R.id.birthday);
		address = (TextView) findViewById(R.id.address);
		// 创建日历的dialog
		datepickrDialog = DatePickerDialog.newInstance(new OnDateSetListener() {

			@Override
			public void onDateSet(DatePickerDialog dialog, int year,
					int monthOfYear, int dayOfMonth) {
				birthday.setText(year + "-" + (monthOfYear + 1) + "-"
						+ dayOfMonth);
			}
		}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar
				.get(Calendar.DAY_OF_MONTH));

		// 创建选择头像的dialog
		choice_photo = (RelativeLayout) LayoutInflater.from(
				EditPersonalInfoActivity.this).inflate(R.layout.choice_photo,
				null);
		camera = (Button) choice_photo.findViewById(R.id.camera);
		album = (Button) choice_photo.findViewById(R.id.album);
		cancel = (Button) choice_photo.findViewById(R.id.cancel);
		dialog = new Dialog(EditPersonalInfoActivity.this);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(choice_photo);

		// 创建选择性别的dialog
		sex_dialog = (RelativeLayout) LayoutInflater.from(
				EditPersonalInfoActivity.this).inflate(
				R.layout.sex_dialog_view, null);
		male = (TextView) sex_dialog.findViewById(R.id.male);
		female = (TextView) sex_dialog.findViewById(R.id.female);
		AlertDialog.Builder builder = new AlertDialog.Builder(
				EditPersonalInfoActivity.this);
		builder.setView(sex_dialog);
		sexDialog = builder.create();

		// 判断有没有SD卡
		isSDCardExit = Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED);
	}

	private void initClick() {
		male.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				sexDialog.dismiss();
				sex.setText("男");
			}
		});

		female.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				sexDialog.dismiss();
				sex.setText("女");
			}
		});

		camera.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!isSDCardExit) {
					Toast.makeText(EditPersonalInfoActivity.this, "请插入存储卡再试",
							Toast.LENGTH_SHORT).show();
					return;
				} else {
					tempFile = new File(Environment
							.getExternalStorageDirectory(), TEMP);
				}
				Intent cameraIntent = new Intent(
						MediaStore.ACTION_IMAGE_CAPTURE);
				cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,
						Uri.fromFile(tempFile));
				startActivityForResult(cameraIntent, CAMERA);
			}
		});

		album.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Intent.ACTION_PICK);
				intent.setType("image/*");
				startActivityForResult(intent, ALBUM);
			}
		});

		cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
	}

	// 点击更换头像
	public void portrait(View v) {
		Window window = dialog.getWindow();
		window.setGravity(Gravity.BOTTOM);
		window.setWindowAnimations(R.style.mydialog);
		dialog.show();
		window.getDecorView().setPadding(0, 0, 0, 0);
		WindowManager.LayoutParams params = window.getAttributes();
		params.width = WindowManager.LayoutParams.MATCH_PARENT;
		params.height = WindowManager.LayoutParams.WRAP_CONTENT;
		window.setAttributes(params);
	}

	// 点击更换生日日期
	public void birthday(View v) {
		datepickrDialog.show(getFragmentManager(), "date");
	}

	// 点击更换地址
	public void address(View v) {
		Intent intent = new Intent(EditPersonalInfoActivity.this,
				TownActivity.class);
		startActivityForResult(intent, ADDRESS);
		overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
	}

	// 点击更换性别
	public void sex(View v) {
		sexDialog.show();
	}

	// 完成修改，并提交
	public void accomplish(View v) {
		// 完成个人信息的编辑
		Toast.makeText(EditPersonalInfoActivity.this, "完成个人信息的编辑",
				Toast.LENGTH_SHORT).show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == ADDRESS && resultCode == RESULT_OK && data != null) {
			Uri addressStr = data.getData();
			address.setText(addressStr.toString());
		}

		if (requestCode == ALBUM && resultCode == RESULT_OK && data != null) {
			Uri uri = data.getData();
			crop(uri);
		}

		if (requestCode == CAMERA && resultCode == RESULT_OK) {
			crop(Uri.fromFile(tempFile));
		}

		if (requestCode == CROP && resultCode == RESULT_OK && data != null) {
			Bitmap bitmap = data.getParcelableExtra("data");
			portrait.setImageBitmap(bitmap);
			try {
				tempFile.delete();
			} catch (Exception e) {
				//没有建过零时文件
			}
			dialog.dismiss();
		}
	}

	/*
	 * 剪切图片
	 */
	private void crop(Uri uri) {
		// 裁剪图片意图
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		// 裁剪框的比例，1：1
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// 裁剪后输出图片的尺寸大小
		intent.putExtra("outputX", 250);
		intent.putExtra("outputY", 250);

		intent.putExtra("outputFormat", "JPEG");// 图片格式
		intent.putExtra("noFaceDetection", true);// 取消人脸识别
		intent.putExtra("return-data", true);
		// 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CUT
		startActivityForResult(intent, CROP);
	}

	// 退出当前Activity
	public void back(View v) {
		finish();
		overridePendingTransition(android.R.anim.slide_in_left,
				android.R.anim.slide_out_right);
	}
}
